from threading import Thread
import serial
import time
import requests

from threading import Thread
class ServerPost(Thread):
    def __init__(self,counter,data):
        Thread.__init__(self)
        self.data = data
        self.counter = counter
    def run(self):
        ipaddr = 'http://negtise2.appspot.com/server_post'    
        r = requests.post(ipaddr, data={'counter':self.counter,'data':self.data})
    #    time.sleep(0.1)
        print self.data,r.text

class ServerGet(Thread):
    def __init__(self,counter,data):
        Thread.__init__(self)
        self.data = data
        self.counter = counter
    def run(self):
        ipaddr = 'http://negtise2.appspot.com/get'
        r = requests.get(ipaddr)

class ReadThread(Thread):
    def __init__(self,serial):
        Thread.__init__(self)
        self.serial = serial
        self.isStop = False
    def run(self):
        line = []
        f = open('a.txt','wb')
        ignore_str = '\x1B\x5B\x30\x6D\x20\x20\x1B\x5B\x31\x3B\x33\x34\x6D'
        while not self.isStop:
            #line = self.serial.readline()
            #print line
            if self.serial.inWaiting():
                a = self.serial.read()
                line.append(a)
                if a == '\n':
                    line = ''.join(line) 
                    line = line.replace(ignore_str,'')
                    print line
                    f.write(line)
                    line = []
            else:
                time.sleep(0.1)
        print 'close'
        f.close()

    def stop(self):
        self.serial.write('\n')
        self.isStop = True

class WriteThread(Thread):
    def __init__(self,serial):
        Thread.__init__(self)
        self.serial = serial
        self.isStop = False
    def run(self):
        while not self.isStop:
            line = raw_input('>>>')
            if line.strip() == 'exit':
                break
            self.serial.write(line)
            self.serial.write('\n')
                        
    def stop(self):
        self.write('\n')
        self.isStop = True

ser = serial.Serial()
ser.baudrate = 115200
ser.port = 4
ser.parity = serial.PARITY_NONE
ser.open()

r = ReadThread(ser)
w = WriteThread(ser)
r.start()
w.start()

w.join()

r.stop()
r.join()

ser.close()
